// import dayjs from 'dayjs';

// const formatTime = (date, template) => dayjs(date).format(template);

/**
 * 格式化价格数额为字符串
 * 可对小数部分进行填充，默认不填充
 * @param price 价格数额，以分为单位!
 * @param fill 是否填充小数部分 0-不填充 1-填充第一位小数 2-填充两位小数
 */
function priceFormat(price, fill = 0) {
  if (isNaN(price) || price === null || price === Infinity) {
    return price;
  }

  let priceFormatValue = Math.round(parseFloat(`${price}`) * 10 ** 8) / 10 ** 8; // 恢复精度丢失
  priceFormatValue = `${Math.ceil(priceFormatValue) / 100}`; // 向上取整，单位转换为元，转换为字符串
  if (fill > 0) {
    // 补充小数位数
    if (priceFormatValue.indexOf('.') === -1) {
      priceFormatValue = `${priceFormatValue}.`;
    }
    const n = fill - priceFormatValue.split('.')[1]?.length;
    for (let i = 0; i < n; i++) {
      priceFormatValue = `${priceFormatValue}0`;
    }
  }
  return priceFormatValue;
}

/**
 * 获取cdn裁剪后链接
 *
 * @param {string} url 基础链接
 * @param {number} width 宽度，单位px
 * @param {number} [height] 可选，高度，不填时与width同值
 */
const cosThumb = (url, width, height = width) => {
  if (url.indexOf('?') > -1) {
    return url;
  }

  if (url.indexOf('http://') === 0) {
    url = url.replace('http://', 'https://');
  }

  return `${url}?imageMogr2/thumbnail/${~~width}x${~~height}`;
};

const get = (source, paths, defaultValue) => {
  if (typeof paths === 'string') {
    paths = paths
      .replace(/\[/g, '.')
      .replace(/\]/g, '')
      .split('.')
      .filter(Boolean);
  }
  const { length } = paths;
  let index = 0;
  while (source != null && index < length) {
    source = source[paths[index++]];
  }
  return source === undefined || index === 0 ? defaultValue : source;
};
let systemWidth = 0;
/** 获取系统宽度，为了减少启动消耗所以在函数里边做初始化 */
export const loadSystemWidth = () => {
  if (systemWidth) {
    return systemWidth;
  }

  try {
    ({ screenWidth: systemWidth, pixelRatio } = uni.getSystemInfoSync());
  } catch (e) {
    systemWidth = 0;
  }
  return systemWidth;
};

/**
 * 转换rpx为px
 *
 * @description
 * 什么时候用？
 * - 布局(width: 172rpx)已经写好, 某些组件只接受px作为style或者prop指定
 *
 */
const rpx2px = (rpx, round = false) => {
  loadSystemWidth();

  // px / systemWidth = rpx / 750
  const result = (rpx * systemWidth) / 750;

  if (round) {
    return Math.floor(result);
  }

  return result;
};

/**
 * 手机号码*加密函数
 * @param {string} phone 电话号
 * @returns
 */
const phoneEncryption = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

// 内置手机号正则字符串
const innerPhoneReg =
  '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$';

/**
 * 手机号正则校验
 * @param phone 手机号
 * @param phoneReg 正则字符串
 * @returns true - 校验通过 false - 校验失败
 */
const phoneRegCheck = (phone) => {
  const phoneRegExp = new RegExp(innerPhoneReg);
  return phoneRegExp.test(phone);
};

/**
 * 日期 时间格式化 星期
 * @param 
 * @param 
 * @returns 
 */

const convertWeek = (targetDay) => {
  let days = ''
  switch (targetDay) {
    case 1:
      days = '周一';
      break;
    case 2:
      days = '周二';
      break;
    case 3:
      days = '周三';
      break;
    case 4:
      days = '周四';
      break;
    case 5:
      days = '周五';
      break;
    case 6:
      days = '周六';
      break;
    case 0:
      days = '周日';
      break;
  }
  return days;
};

/**
 * @description:消息提示  showToast
 * @param {String }title:提示文字
 */
export const showToast = (title) => {
  return uni.showToast({
    title,
    icon: 'none',
    image: '',
    duration: 3000,
    mask: false,
  });
}

/**
 * @description:提示消息---加载
 * @param {String }title:提示文字
 */
export const showLoading = (title) => {
  return uni.showLoading({
    title,
    mask: true,
  });
};
/**
 * @description:隐藏loading
 * @param {}
 */
export const hideLoading = () => uni.hideLoading();

/**
 * @description: 模态框打开授权设置页面
 * @param {*}
 * @return {*}
 */

export const showModal = () => {
  return uni.showModal({
    title: "提示",
    content: "请允许授权获取您的地理位置，才能查看终端位置",
    showCancel: true,
    cancelText: "取消",
    cancelColor: "#000000",
    confirmText: "确定",
    confirmColor: "#3CC51F",
    success(res) {
      if (res.confirm) {
        uni.openSetting();
      }
    },
    fail: () => {
      showToast("未获取定位权限，请重新打开设置");
      uni.openSetting();
    },
    complete: () => { },
  });
}

/**
 * @description: 获取位置信息授权
 * @param {*}
 * @return {*}
 */
export const getLocation = () => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: "gcj02", // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 uni.openLocation 的坐标
      success: function (res) {
        // console.log("getLocation-success", res);
        let { latitude, longitude } = res;
        uni.setStorageSync('latitude', latitude);
        uni.setStorageSync('longitude', longitude);
        resolve(res);
      },
      fail: function (err) {
        let latitude = uni.getStorageSync('latitude');
        let longitude = uni.getStorageSync('longitude');
        console.log("getLocation-fail", latitude, longitude);
        reject({ latitude, longitude });
      },
    });
  })
}

/**
 * @description: 防抖
 * @param {*}
 * @return {*}
 */
export const debounce = (func, delay) => {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

export const arrayUnique  = (arr, name) => {
	let hash = {}
	return arr.reduce( (acc, cru, index) => {
		if ( !hash[cru[name]] ) {
			hash[cru[name]] = {index:acc.length} 
			acc.push(cru)
		}else{
			acc.splice( hash[cru[name]]['index'], 1, cru)
		}
		return acc;
	}, [])
};

module.exports = {
  // formatTime,
  priceFormat,
  cosThumb,
  get,
  rpx2px,
  phoneEncryption,
  phoneRegCheck,
  convertWeek,
  showToast,
  showLoading,
  hideLoading,
  getLocation,
  showModal,
  debounce,
  arrayUnique
};
